package com.sprite.framework.component;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.w3c.dom.Element;

import com.sprite.utils.UtilBeans;
import com.sprite.utils.UtilClass;
import com.sprite.utils.UtilProperties;
import com.sprite.utils.UtilURL;

public interface ConfigHandler {

	void handle(Element element, SpriteConfig config);
	
	Map<String, ConfigHandler> _handlers = new HashMap<>();
	
	static Map<String, ConfigHandler> getHandlers() throws SpriteException{
		if(_handlers.isEmpty()) {
			synchronized (_handlers) {
				try {
					List<URL> urls = UtilURL.fromResources("META-INF/sprite.handlers");
					for(URL url : urls) {
						Properties p = UtilProperties.getProperties(url);
						for(String key : p.stringPropertyNames()) {
							if(UtilClass.isPresent(p.getProperty(key))) {
								_handlers.put(key, (ConfigHandler) UtilBeans.instance(UtilClass.forName(p.getProperty(key))));
							}
						}
					}
					
					return _handlers;
				} catch (Exception e) {
					throw new SpriteException("Error scanning the component config file ", e);
				}
			}
		}
		
		return _handlers;
	}
	
	static ConfigHandler getHandler(String key) throws SpriteException{
		getHandlers();
		ConfigHandler handler =  _handlers.get(key);
		if(handler == null) {
			throw new SpriteException("not found ConfigHandler: "+key);
		}
		
		return handler;
	}
}
